package org.ichihamigua.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * 鉴权过滤器
 * @author rainkyzhong
 * @date 2023/06/15
 */
@Component
@Slf4j
public class AuthenticationFilter implements WebFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {

        //设置跨域
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse httpResponse = exchange.getResponse();
        HttpHeaders headers = httpResponse.getHeaders();
        headers.add("Access-Control-Allow-Origin", "*");
        headers.set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authentication, Uid, Lid, Login-Type");
        headers.set("Access-Control-Allow-Methods", "GET, PUT, OPTIONS, POST, DELETE");


        //处理预检
        if (request.getMethod().equals(HttpMethod.OPTIONS)) {
            return exchange.getResponse().setComplete();
        }




        return chain.filter(exchange);
    }

    /*
    数字越小，优先级越高
     */
    @Override
    public int getOrder() {
        return 1;
    }
}